﻿using DFGK.IService.LY;
using DFGK.Service;
using DFGK.Service.LY;
using DFGK_WMS.Common;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Models.LyModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetTaste;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI.Controllers.PC.装备智能采购辅助软件
{
    /// <summary>
    /// 采购标准制定管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "PC")]
    public class ProcurementStandardController : BaseController
    {
        private readonly IPurchaseStandardService _purchaseStandardService;
        public ProcurementStandardController(IWebHostEnvironment environment, IPurchaseStandardService purchaseStandardService) : base(environment)
        {
            _purchaseStandardService = purchaseStandardService;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="name"></param>
        /// <param name="totalCount"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPurchaseStandardPageData(string? name, int pageIndex = 1, int pageSize = 20)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                BaseResult.Result("400", "分页条件有误！");
            }
            var list = _purchaseStandardService.GetPurchaseStandardPageData(name, out var totalCount, pageIndex, pageSize);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));

        }

        /// <summary>
        /// 采购计划导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PurchaseStandardImport(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                string uname = HttpContext.User.FindFirstValue("UserName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }
                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;

                List<PurchaseStandard> stuList = new();
                for (int i = 1; i <= totalRow; i++)
                {

                    IRow row = sheet.GetRow(i);
                    string? StandardName = row.GetCell(0)?.StringCellValue;
                    double? EmployeeCount = row.GetCell(1)?.NumericCellValue;
                    string? Description = row.GetCell(2)?.StringCellValue;
                  

                    var purchase = new PurchaseStandard
                    {
                        StandardName = StandardName,
                        EmployeeCount = (int)EmployeeCount,
                        Description = Description,

                    };
                    stuList.Add(purchase);
                }
                if (stuList.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(false, "导入失败！" + message, "500"));
                }
                bool result = _purchaseStandardService.AddPurchase(stuList);
                wb.Close();
                if (result)
                {
                    return Ok(BaseResult.Result(true, "导入成功！" + message, "200"));
                }
                return Ok(BaseResult.Result(stuList, "导入失败！", "500"));
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 采购计划导出
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult PurchaseStandardDown()
        {

            var list = _purchaseStandardService.GetPurchaseStandardPageDown();
            if (list != null)
            {
                return PurchaseStandardDown(list);
            }
            return Ok();
        }

        /// <summary>
        /// 采购标准制定管理导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult InvDownPurchaseStandardPageData(string? name, int pageIndex = 1, int pageSize = 20)
        {

            var list = _purchaseStandardService.GetPurchaseStandardPageData(name, out var totalCount, pageIndex, pageSize);
            if (list != null)
            {
                return InvDownPurchaseStandardPageData(list);
            }
            return Ok();
        }






        /// <summary>
        /// 新增或修改采购标准制定管理
        /// </summary>
        /// <param name="model"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PurchaseStandardData(PurchaseStandard model)
        {
            if (model.Id > 0)
            {
                model.ModifyDate = DateTime.Now;
                model.ModifyUserId = base.BaseGetNowUserId();
                model.ModifyUserName = base.BaseGetNowUserName();
                bool result = _purchaseStandardService.PurchaseStandardData(model, out string message);
                if (result)
                {
                    return Ok(BaseResult.Result(true, "修改成功！", "200"));
                }
                return Ok(BaseResult.Result(false, "修改失败！" + message, "500"));
            }
            else
            {
                model.CreateUserName = base.BaseGetNowUserName();
                model.CreateUserId = base.BaseGetNowUserId();
                model.CreateDate = DateTime.Now;
                bool result = _purchaseStandardService.PurchaseStandardData(model, out string message);
                if (result)
                {
                    return Ok(BaseResult.Result(true, "添加成功！", "200"));
                }
                return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
            }
            
        }
        /// <summary>
        /// 根据id查询
        /// </summary>
        /// <param name="purchaseStandardId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPurchaseStandard(long purchaseStandardId)
        {
            if (purchaseStandardId <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var PurchaseStandard = _purchaseStandardService.GetPurchaseStandard(purchaseStandardId);
            if (PurchaseStandard != null)
            {
                return Ok(BaseResult.Result(PurchaseStandard, "查询成功！", "200", 0));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// 删除采购标准制定
        /// </summary>
        /// <param name="shareFileId"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelPurchaseStandard(long purchaseStandardId)
        {
            if (purchaseStandardId <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var result = _purchaseStandardService.DelPurchaseStandard(purchaseStandardId);
            if (result)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }

    }
}
